package com.blyat.xsoft.kernel.component.security;


import com.blyat.xsoft.kernel.component.security.exception.SecureException;
import com.blyat.xsoft.kernel.exception.code.DefaultErrorResult;
import com.blyat.xsoft.kernel.restful.view.ResultModel;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * @author syh
 * @date 2019/8/21
 **/
public class SecurityLoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    @Override
    protected void handle(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException {

        if (response.isCommitted()) {
            throw new SecureException(DefaultErrorResult.HTTP_COMMITED);
        }

        Map<String, Object> result = Maps.newHashMapWithExpectedSize(3);
        result.put("user", authentication.getPrincipal());


        response.setContentType("application/json;charset=utf-8");
        ObjectMapper om = new ObjectMapper();
        PrintWriter out = response.getWriter();
        out.write(om.writeValueAsString(ResultModel.SUCCESS("登录成功", result)));
        out.flush();
        out.close();
    }
}
